package com.ruoyi.web.sso.api;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.core.config.TokenConfig;
import com.ruoyi.web.sso.common.util.BusinessException;
import com.ruoyi.web.sso.common.util.ErrorCode;
import com.ruoyi.web.sso.common.util.PasswordUtil;
import com.ruoyi.web.sso.domain.Alliance;
import com.ruoyi.web.sso.domain.DTO.StatusResponse;
import com.ruoyi.web.sso.domain.Staff;
import com.ruoyi.web.sso.domain.vo.StaffDetails;
import com.ruoyi.web.sso.service.IAllianceService;
import com.ruoyi.web.sso.service.IStaffService;
import com.ruoyi.web.sso.service.SendSmsService;
import com.ruoyi.web.sso.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 短信验证Controller
 *
 * @author ruoyi
 * @date 2022-01-08
 */
@Controller
@RequestMapping("/api/sso/sms")
@Api(tags = "短信接口")
public class ApiSmsController extends BaseController {

    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IStaffService staffService;

    /**
     * 发送短信验证码
     */
    @PostMapping("/sendSms")
    @ResponseBody
    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码")
    public StatusResponse sendSms(String phone) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        Long expiredTime = Long.valueOf(2592000);
        redisTemplate.opsForValue().set(phone, code, expiredTime, TimeUnit.SECONDS);
        Map map = ImmutableMap.of("code", code);
        String param = StringUtil.toJson(map);
        sendSmsService.sendSms(phone, "SMS_242820780", param);
        return StatusResponse.success(true);
    }

    /**
     * 重置密码
     */
    @PostMapping("/validSmsCode")
    @ResponseBody
    @ApiOperation(value = "重置密码", notes = "重置密码")
    public StatusResponse sendSms(String phone, int code) {
        int code1 = (Integer) redisTemplate.opsForValue().get(phone);
        if (code1 == code) {
            Staff staff = staffService.selectMobileByStaff(phone);
            if (Objects.nonNull(staff)){
                staff.setPassword(PasswordUtil.encode("Abc@123456").toLowerCase());
                staffService.updatePassword(staff);
                return StatusResponse.success("重置成功");
            }else {
                throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "账号不存在");
            }
        }else {
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "验证码错误");
        }
    }


    @PostMapping("/forgetPassword")
    @ResponseBody
    @ApiOperation(value = "验证码修改密码", notes = "验证码修改密码")
    public StatusResponse forgetPassword( String phone, String verifyCode, String newPassword){
        int code1 = (Integer) redisTemplate.opsForValue().get(phone);
        if (code1 == Integer.valueOf(verifyCode)) {
            Staff staff = staffService.selectMobileByStaff(phone);
            // 校验密码复杂度
//            if (!isValidPassword(newPassword)) {
//                throw new BusinessException(ErrorCode.LOGIN_LOCKED1,"密码需包含大小写、数字、特殊字符中的至少2种，且长度≥8位");
//            }
            if (Objects.nonNull(staff)){
                staff.setPassword(newPassword);
                staffService.updatePassword(staff);
                return StatusResponse.success("重置成功");
            }else {
                throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "账号不存在");
            }
        }else {
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "验证码错误");
        }
    }

    /**
     * 校验密码复杂度：至少8位，且包含大小写、数字、特殊字符中的至少2种组合
     */
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }

        int strength = 0;
        if (password.matches(".*[A-Z].*")) strength++; // 大写字母
        if (password.matches(".*[a-z].*")) strength++; // 小写字母
        if (password.matches(".*\\d.*")) strength++;   // 数字
        if (password.matches(".*[^A-Za-z\\d].*")) strength++; // 特殊字符

        return strength >= 2; // 至少满足两种组合
    }

}
